'use strict'

let nodeMgr = require('./nodeMgr')
let playerSessionMgr = require('./playerSessionMgr')
let sceneMgr = require('./sceneMgr')
let route = require('./route')
var http = require('http');

//新建角色
route.setNotLogin('createPlayer', function(session, msg, next) {
  let password = msg.password
  let username = msg.username
  http.get('http://127.0.0.1:12340/verifyUser?name=' + username + '&pwd=' + password, function(res) {
    res.on('data', function(data) {
      data = JSON.parse(data)
      if (data.error === 0) {
        msg.userId = data.userId
        let node = nodeMgr.nodesName['node1']
        node.send('', 'createPlayer', msg, function(res) {
          next(res)
        })
      } else {
        next(data.error)
      }
    })
  }).on('error', function(e) {
    next(10)
  })
})

//角色登陆
route.setNotLogin('playerLogin', function(session, msg, next) {
  let password = msg.password
  let username = msg.username
  http.get('http://127.0.0.1:12340/verifyUser?name=' + username + '&pwd=' + password, function(res) {
    res.on('data', function(data) {
      data = JSON.parse(data)
      if (data.error === 0) {
        let sessionId = session.id
        let node = nodeMgr.nodesName['node1']
        node.send('', 'playerLogin', {
          userId: data.userId
        }, function(res) {
          if (res.error === 0) {
            let pid = res._id
            let ret = playerSessionMgr.bind(sessionId, pid)
            if(ret === -1){
              return
            }
            let sceneId = res.basicInfo.sceneId
            sceneMgr.getSceneSerById(sceneId).addClient(session)
            next(res)
          } else {
            next({
              error: res.error
            })
          }
        })
      } else {
        next(data.error)
      }
    })
  }).on('error', function(e) {
    next(10)
  })
})

//心跳
route.set('heartbeat', function(session, msg, next) {
  session.heartbeat = 0
  next(0)
})
